import axios, { AxiosRequestConfig } from "axios";
import { message } from "antd";
import { useAppStore } from "@/stores";
import i18n from "@/i18n";

export interface ResponseData<T> {
  code: number;
  success: boolean;
  data: T;
  message: string;
}

export const service = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
  timeout: 10000,
});

service.interceptors.request.use((config) => {
  const token = useAppStore.getState().getToken();
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

service.interceptors.response.use(
  (response) => {
    const res = response.data;
    if (!res.success) {
      message.error(res.message || i18n.t("common.requestFailed"));
      return Promise.reject(new Error(res.message));
    }
    return response;
  },
  (error) => {
    if (error.response?.status === 401) {
      // 处理未授权
      useAppStore.getState().logout();
    }
    message.error(
      error.response?.data?.message || i18n.t("common.networkError")
    );
    return Promise.reject(error);
  }
);

export async function request<T>(options: AxiosRequestConfig) {
  return await service
    .request<ResponseData<T | any>>(options)
    .then((res) => res.data);
}

export async function get<T>(url: string, params = {}) {
  return request<T>({ method: "GET", url, params });
}

export async function post<T>(url: string, data = {}, params = {}) {
  return request<T>({ method: "POST", url, data, params });
}

export async function put<T>(url: string, data = {}, headers = {}) {
  return request<T>({ method: "PUT", url, data, headers });
}

export async function del<T>(url: string, data = {}, headers = {}) {
  return request<T>({ method: "DELETE", url, data, headers });
}
